<template>
  <q-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    position="right"
    class="details-drawer-dialog"
  >
    <q-card class="details-drawer-card">
      <!-- 好友详情抽屉 -->
      <div v-if="type === 'User'" class="drawer-content">
        <div class="drawer-header">
          <q-btn icon="close" flat round dense @click="$emit('update:modelValue', false)" />
        </div>
        
        <div class="drawer-body">
          <!-- 头像和名称 -->
          <div class="user-header-section">
            <div class="user-avatar-item">
              <q-avatar 
                class="user-avatar-large" 
                size="52px"
                :style="getAvatarStyle(targetId || '')"
              >
                {{ getUserInitial(targetId || '') }}
              </q-avatar>
              <div class="user-name-large">{{ targetName }}</div>
            </div>
            <div class="add-contact-btn" @click="$emit('add-contact')">
              <div class="add-icon-wrapper">
                <q-icon name="add" size="20px" />
              </div>
              <div class="add-text">添加</div>
            </div>
          </div>

          <!-- 设置项容器 -->
          <div class="drawer-settings-container">
            <q-separator class="drawer-separator" />

            <!-- 查找聊天记录 -->
            <div class="drawer-item clickable" @click="$emit('search-chat-history')">
              <div class="drawer-item-label">查找聊天记录</div>
              <q-icon name="chevron_right" size="20px" color="#C7C7CC" />
            </div>

            <q-separator class="drawer-separator" />

            <!-- 消息免打扰 -->
            <div class="drawer-item">
              <div class="drawer-item-label">消息免打扰</div>
              <q-toggle :model-value="doNotDisturb" @update:model-value="$emit('update:doNotDisturb', $event)" />
            </div>

            <!-- 置顶聊天 -->
            <div class="drawer-item">
              <div class="drawer-item-label">置顶聊天</div>
              <q-toggle :model-value="pinChat" @update:model-value="$emit('update:pinChat', $event)" />
            </div>
          </div>

          <q-separator class="drawer-separator drawer-separator-spacing" />

          <!-- 清空聊天记录 -->
          <div class="drawer-item drawer-item-danger" @click="$emit('clear-chat-history')">
            <div class="drawer-item-label">清空聊天记录</div>
          </div>
        </div>
      </div>

      <!-- 群组详情抽屉 -->
      <div v-else-if="type === 'Group'" class="drawer-content">
        <div class="drawer-header">
          <q-btn icon="close" flat round dense @click="$emit('update:modelValue', false)" />
        </div>
        
        <div class="drawer-body">
          <!-- 搜索群成员 -->
          <q-input
            :model-value="groupMemberSearch"
            @update:model-value="$emit('update:groupMemberSearch', $event)"
            placeholder="搜索群成员"
            outlined
            dense
            class="member-search-input"
            autocomplete="off"
            clearable
          >
            <template v-slot:prepend>
              <q-icon name="search" />
            </template>
          </q-input>

          <!-- 群成员网格（参考微信设计，4列布局，最多显示4行，每行4个，共16个成员位置，然后"添加"按钮） -->
          <div class="members-grid" :style="{ '--member-count': totalMembersCount, '--displayed-count': displayedMembers.length }">
            <!-- 先显示所有成员 -->
            <template v-if="displayedMembers.length > 0">
              <div
                v-for="member in displayedMembers"
                :key="member.member_id"
                class="member-grid-item"
              >
                <q-avatar class="member-avatar-grid" size="45px">
                  <div 
                    class="avatar-placeholder"
                    :style="getAvatarStyle((member as any).displayName || member.alias || member.member_id)"
                  >
                    {{ ((member as any).displayName?.[0] || member.alias?.[0] || member.member_id[0] || 'M').toUpperCase() }}
                  </div>
                </q-avatar>
                <div class="member-name-grid">{{ (member as any).displayName || member.alias || member.member_id }}</div>
                <!-- 群主/管理员显示移除按钮（不能移除自己） -->
                <div 
                  v-if="canRemoveMember && (!props.currentUserId || member.member_id !== props.currentUserId)"
                  class="member-remove-btn"
                  @click.stop="$emit('remove-group-member', member.member_id)"
                >
                  <q-icon name="remove" size="14px" />
                </div>
              </div>
            </template>
            <!-- 添加成员按钮（所有人可见，始终显示） -->
            <div class="member-grid-item add-member-item" @click="$emit('add-group-member')">
              <div class="add-member-icon-wrapper">
                <q-icon name="add" size="20px" />
              </div>
              <div class="member-name-grid">添加</div>
            </div>
          </div>

          <!-- 展开更多/收起按钮（超过16个成员时显示） -->
          <div v-if="totalMembersCount > 16" class="expand-more-btn" @click="$emit('toggle-show-all-members')">
            <span>{{ showAllMembers ? '收起' : '展开更多' }}</span>
            <q-icon :name="showAllMembers ? 'expand_less' : 'expand_more'" size="20px" />
          </div>

          <q-separator class="drawer-separator" />

          <!-- 群聊名称（可编辑，仅群主） -->
          <div 
            class="drawer-item" 
            :class="{ 'clickable': isGroupOwner }"
            @click="isGroupOwner && handleEditGroupName()"
          >
            <div class="drawer-item-label">群聊名称</div>
            <div class="drawer-item-value">{{ groupDetails?.group_name || targetName }}</div>
            <q-icon v-if="isGroupOwner" name="chevron_right" size="20px" color="#C7C7CC" />
          </div>

          <!-- 群公告 -->
          <div class="drawer-item clickable" @click="$emit('view-group-announcement')">
            <div class="drawer-item-label">群公告</div>
            <div class="drawer-item-value">{{ groupDetails?.announcement || '暂无公告' }}</div>
            <q-icon name="chevron_right" size="20px" />
          </div>

          <!-- 备注（可编辑） -->
          <div class="drawer-item clickable" @click="handleEditRemark">
            <div class="drawer-item-label">备注</div>
            <div class="drawer-item-value">{{ groupChatRemark || '群聊的备注仅自己可见' }}</div>
            <q-icon name="chevron_right" size="20px" color="#C7C7CC" />
          </div>

          <!-- 查找聊天记录 -->
          <div class="drawer-item clickable" @click="$emit('search-chat-history')">
            <div class="drawer-item-label">查找聊天记录</div>
            <q-icon name="chevron_right" size="20px" />
          </div>

          <q-separator class="drawer-separator drawer-separator-spacing" />

          <!-- 危险操作区域 -->
          <div class="danger-actions-container">
            <!-- 群主显示解散群组，普通成员显示退出群聊 -->
            <div v-if="isGroupOwner" class="drawer-item drawer-item-danger" @click="$emit('dissolve-group')">
              <div class="drawer-item-label">解散群组</div>
            </div>
            <div v-else class="drawer-item drawer-item-danger" @click="$emit('leave-group')">
              <div class="drawer-item-label">退出群聊</div>
            </div>
            <div class="danger-action-divider"></div>
            <!-- 清空聊天记录 -->
            <div class="drawer-item drawer-item-danger" @click="$emit('clear-chat-history')">
              <div class="drawer-item-label">清空聊天记录</div>
            </div>
          </div>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { getAvatarStyle } from '@/utils/avatar'

const props = defineProps<{
  modelValue: boolean
  type: 'User' | 'Group' | null
  targetId: string | null
  targetName: string
  doNotDisturb: boolean
  pinChat: boolean
  groupMemberSearch: string
  groupMembers: any[]
  groupDetails: any
  showAllMembers: boolean
  isGroupOwner?: boolean // 是否是群主（仅在群组类型时使用）
  groupChatRemark?: string // 群聊备注
  currentUserId?: string // 当前用户ID（用于判断是否可以移除自己）
  getUserInitial: (userId: string | null) => string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'add-contact': []
  'search-chat-history': []
  'update:doNotDisturb': [value: boolean]
  'update:pinChat': [value: boolean]
  'update:groupMemberSearch': [value: string]
  'add-group-member': []
  'remove-group-member': [memberId: string]
  'show-remove-member-dialog': []
  'toggle-show-all-members': []
  'view-group-announcement': []
  'dissolve-group': []
  'leave-group': []
  'clear-chat-history': []
  'update-group-name': [groupId: string, newName: string]
  'update-group-remark': [chatId: string, remark: string | null]
}>()

// 计算是否可以移除成员（群主或管理员）
// 需要检查当前用户是否是群主或管理员
// 注意：这里通过检查是否有管理员成员来判断，但更准确的方式是从父组件传入当前用户是否是管理员
const canRemoveMember = computed(() => {
  // 如果当前用户是群主，可以移除成员
  if (props.isGroupOwner === true) {
    return true
  }
  // 检查是否有管理员（role === 2），如果有，说明可能有管理员权限
  // 但这里无法确定当前用户是否是管理员，所以暂时只检查 isGroupOwner
  // 如果需要更精确，需要从父组件传入 isAdmin 或 canRemoveMember prop
  // 为了简化，这里先只检查 isGroupOwner
  // 实际上，如果用户是管理员，isGroupOwner 可能为 false，但应该也能移除成员
  // 这个逻辑应该在父组件中计算，然后作为 prop 传入
  return props.isGroupOwner === true // 暂时只检查是否是群主
})

// 处理编辑群组名称
const handleEditGroupName = () => {
  if (props.type === 'Group' && props.targetId) {
    emit('update-group-name', props.targetId, props.groupDetails?.group_name || props.targetName)
  }
}

// 处理编辑群聊备注
const handleEditRemark = () => {
  if (props.type === 'Group' && props.targetId) {
    emit('update-group-remark', props.targetId, props.groupChatRemark || null)
  }
}

// 过滤群成员（根据搜索条件）
const filteredMembers = computed(() => {
  let members = props.groupMembers || []
  
  // 调试：输出成员数据
  if (props.type === 'Group') {
    console.log('DetailsDrawer - filteredMembers 计算:', {
      groupMembers: props.groupMembers,
      groupMembersLength: props.groupMembers?.length || 0,
      groupMembersType: Array.isArray(props.groupMembers) ? 'array' : typeof props.groupMembers,
      groupMemberSearch: props.groupMemberSearch,
      membersAfterFilter: members.length
    })
  }
  
  if (props.groupMemberSearch) {
    const query = props.groupMemberSearch.toLowerCase()
    members = members.filter(
      (m) =>
        (m.member_id && m.member_id.toLowerCase().includes(query)) ||
        (m.alias && m.alias.toLowerCase().includes(query)) ||
        ((m as any).displayName && (m as any).displayName.toLowerCase().includes(query))
    )
  }
  
  return members
})

// 计算总成员数（包括添加按钮）
const totalMembersCount = computed(() => {
  return filteredMembers.value.length
})

// 显示的成员列表（根据展开/折叠状态）
const displayedMembers = computed(() => {
  let members = filteredMembers.value
  
  // 默认折叠：显示前16个成员（4行 x 4列），"添加"按钮会在第17个位置
  // 如果展开，显示所有成员
  // 注意：如果成员数量正好是16个或更少，显示所有成员，然后"添加"按钮
  // 如果成员数量超过16个且没有展开，只显示前16个成员，然后"添加"按钮
  if (!props.showAllMembers && members.length > 16) {
    members = members.slice(0, 16)
  }
  
  // 调试：输出显示的成员
  if (props.type === 'Group') {
    console.log('DetailsDrawer - displayedMembers 计算:', {
      filteredCount: filteredMembers.value.length,
      displayedCount: members.length,
      showAllMembers: props.showAllMembers,
      members: members.map(m => ({
        member_id: m.member_id,
        name: (m as any).displayName || m.alias || m.member_id
      }))
    })
  }
  
  return members
})
</script>

<style lang="sass" scoped>
// 详情抽屉样式（使用 q-dialog 实现，完全覆盖，无留白）
.details-drawer-dialog
  :deep(.q-dialog)
    margin: 0 !important
    padding: 0 !important
    max-width: none !important
    max-height: none !important
    z-index: 7000 !important
    
  :deep(.q-dialog__inner)
    justify-content: flex-end !important
    align-items: stretch !important
    padding: 0 !important
    margin: 0 !important
    max-width: none !important
    max-height: none !important
    width: 100vw !important
    height: 100vh !important
    position: fixed !important
    top: 0 !important
    left: 0 !important
    right: 0 !important
    bottom: 0 !important
    overflow: hidden !important
    
  :deep(.q-dialog__backdrop)
    background: rgba(0, 0, 0, 0.25) !important
    position: fixed !important
    top: 0 !important
    left: 0 !important
    right: 0 !important
    bottom: 0 !important
    width: 100vw !important
    height: 100vh !important
    margin: 0 !important
    padding: 0 !important
    // 遮罩层覆盖所有内容，包括导航栏，让导航栏看起来变暗
    // z-index 需要低于抽屉但高于其他内容
    z-index: 6999 !important
    pointer-events: auto !important
    // 确保遮罩层覆盖整个视口，包括导航栏
    transform: none !important
    // 确保遮罩层在 body 层级，覆盖所有内容
    inset: 0 !important

.details-drawer-card
  border-radius: 0 !important
  margin: 0 !important
  padding: 0 !important
  height: 100vh !important
  max-height: 100vh !important
  width: 280px !important
  min-width: 280px !important
  max-width: 280px !important
  display: flex !important
  flex-direction: column !important
  background: #EDEDED !important
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.08) !important
  flex-shrink: 0 !important
  position: absolute !important
  top: 0 !important
  right: 0 !important
  bottom: 0 !important
  overflow: hidden !important
  z-index: 7001 !important
  // 确保抽屉在遮罩之上，保持明亮
  
  :deep(.q-card__section)
    padding: 0
    margin: 0
  
  .drawer-content
    height: 100%
    width: 100%
    display: flex
    flex-direction: column
    background: #EDEDED
    margin: 0
    padding: 0
    
  .drawer-header
    padding: 12px 16px
    display: flex
    justify-content: flex-end
    border-bottom: 1px solid rgba(0, 0, 0, 0.06)
    background: #EDEDED
    
    :deep(.q-btn)
      color: #666666 !important
      background: transparent !important
      
      &:hover
        background: rgba(0, 0, 0, 0.03) !important
        color: #191919 !important
      
      &:active,
      &:focus
        background: rgba(0, 0, 0, 0.05) !important
        color: #191919 !important
        box-shadow: none !important
        outline: none !important
    
  .drawer-body
    flex: 1
    overflow-y: auto
    padding: 0
    background: #EDEDED
    width: 100%
    box-sizing: border-box
    
    // 设置项容器
    > .drawer-item:first-of-type
      margin-top: 0
      
  // 设置项容器
  .drawer-settings-container
    background: #F5F5F5
    margin: 0
    
  // 好友详情样式
  .user-header-section
    display: flex
    flex-direction: row
    align-items: flex-start
    justify-content: center
    padding: 20px 16px 16px 16px
    gap: 20px
    background: #F5F5F5
    
    .user-avatar-item
      display: flex
      flex-direction: column
      align-items: center
      gap: 8px
      flex: 0 0 auto
      
    .user-avatar-large
      color: white
      font-weight: 600
      font-size: 22px
      border-radius: 6px
      overflow: hidden
      
    .user-name-large
      font-size: 14px
      font-weight: 400
      color: #191919
      letter-spacing: -0.1px
      text-align: center
      width: 52px
      overflow: hidden
      text-overflow: ellipsis
      white-space: nowrap
      
    .add-contact-btn
      display: flex
      flex-direction: column
      align-items: center
      gap: 8px
      cursor: pointer
      padding: 0
      transition: opacity 0.2s ease
      flex: 0 0 auto
      
      &:hover
        opacity: 0.7
      
      .add-icon-wrapper
        width: 52px
        height: 52px
        border: 2px dashed #D1D1D6
        border-radius: 6px
        display: flex
        align-items: center
        justify-content: center
        color: #8E8E93
        background: #F5F5F5
        transition: all 0.2s ease
        
        &:hover
          border-color: #6B9BD1
          color: #6B9BD1
          background: #F0F4F8
        
      .add-text
        font-size: 12px
        color: #8E8E93
        font-weight: 400
        
  // 群组详情样式
  .member-search-input
    margin: 16px
    margin-bottom: 16px
    
  .members-grid
    display: grid
    grid-template-columns: repeat(4, 1fr)
    gap: 12px
    margin: 0 16px 16px 16px
    min-height: 80px
    
    .member-grid-item
      display: flex
      flex-direction: column
      align-items: center
      gap: 8px
      cursor: pointer
      
      .member-avatar-grid
        color: white
        font-weight: 600
        width: 45px
        height: 45px
        
      .avatar-placeholder
        width: 100%
        height: 100%
        border-radius: 50%
        
      .member-name-grid
        font-size: 12px
        color: #191919
        text-align: center
        overflow: hidden
        text-overflow: ellipsis
        white-space: nowrap
        width: 100%
        
      &.add-member-item
        .add-member-icon-wrapper
          width: 45px
          height: 45px
          border: 2px dashed #C7C7CC
          border-radius: 50%
          display: flex
          align-items: center
          justify-content: center
          color: #8E8E93
          background: transparent
          
      .member-remove-btn
        position: absolute
        top: -4px
        right: -4px
        width: 18px
        height: 18px
        border-radius: 50%
        background: #C62828
        color: white
        display: flex
        align-items: center
        justify-content: center
        cursor: pointer
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15)
        transition: transform 0.2s ease
        
        &:hover
          transform: scale(1.1)
          
    .member-grid-item
      position: relative
          
  .expand-more-btn
    display: flex
    align-items: center
    justify-content: center
    gap: 8px
    padding: 12px
    color: #6B9BD1
    font-size: 14px
    cursor: pointer
    margin-bottom: 16px
    transition: opacity 0.2s ease
    
    &:hover
      opacity: 0.7
    
  // 通用抽屉项样式
  .drawer-separator
    margin: 0
    background: rgba(0, 0, 0, 0.08)
    height: 0.5px
    
    // 危险操作容器前的分隔线改为间距
    &.drawer-separator-spacing
      height: 8px
      border: none
      background: transparent
      margin: 0
    
  // 危险操作容器（参考微信设计）
  .danger-actions-container
    background: #F5F5F5
    border-radius: 8px
    margin: 8px 0
    overflow: hidden
    border: none
    box-shadow: 0 0 0 0.5px rgba(0, 0, 0, 0.06)
    
    .drawer-item
      margin: 0
      padding: 14px 16px
      border-bottom: none
      transition: background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1)
      cursor: pointer
      display: flex
      align-items: center
      justify-content: center
      position: relative
      
      &.drawer-item-danger
        .drawer-item-label
          color: #C62828
          font-weight: 500
          font-size: 16px
          text-align: center
          width: 100%
          letter-spacing: 0.1px
      
      &:hover
        background: rgba(198, 40, 40, 0.04)
      
      &:active
        background: rgba(198, 40, 40, 0.06)
        transition: background-color 0.1s ease
    
    .danger-action-divider
      height: 0.5px
      background: rgba(0, 0, 0, 0.1)
      margin: 0 16px
    
  .drawer-item
    display: flex
    align-items: center
    justify-content: space-between
    padding: 13px 16px
    background: #F5F5F5
    transition: background-color 0.2s ease
    
    &.clickable
      cursor: pointer
      
      &:hover
        background: rgba(0, 0, 0, 0.02)
      
      &:active
        background: rgba(0, 0, 0, 0.04)
        
    &.drawer-item-danger
      cursor: pointer
      
      .drawer-item-label
        color: #C62828
        font-weight: 500
        
      &:hover
        background: rgba(198, 40, 40, 0.04)
      
      &:active
        background: rgba(198, 40, 40, 0.06)
        
    .drawer-item-label
      font-size: 15px
      font-weight: 400
      color: #191919
      letter-spacing: -0.1px
      
    .drawer-item-value
      font-size: 14px
      color: #8E8E93
      text-align: right
      flex: 1
      margin-right: 8px
      overflow: hidden
      text-overflow: ellipsis
      white-space: nowrap

.avatar-placeholder
  width: 100%
  height: 100%
  display: flex
  align-items: center
  justify-content: center
  color: white
  font-weight: 500
  font-size: 18px
  border-radius: 50%
  overflow: hidden
</style>

